package com.DosonLeung.homeschoolcommunication.Models;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import com.DosonLeung.homeschoolcommunication.Constant.UrlConstant;
import com.DosonLeung.homeschoolcommunication.Constant.UserConstant;
import com.DosonLeung.homeschoolcommunication.Utils.NetWorkUtil;
import com.DosonLeung.homeschoolcommunication.Utils.StorageUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;

/**
 * Created by DosonLeung on 2014/10/21.
 */
public class UserModel{

    //登录方法
    public static void loginByPassword(final String userNumber, final String passWord,final Handler mhandler){
        final String url = String.format(UrlConstant.loginUrl,userNumber,passWord);
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                JSONObject jsonObject;
                String result;
                String token;
                try {
                    result = NetWorkUtil.httpGet(url);
                    if (result != null) {
                        if (!result.equalsIgnoreCase("wrong password")) {
                            jsonObject = new JSONObject(result);
                            token = jsonObject.getString("token");
                            UserConstant.USER_TOKEN = token;
                            UserConstant.USER_ACCOUNT = userNumber;
                            UserConstant.USER_PASSWORD = passWord;
                            msg.what = 0x200;
                        } else {
                            msg.what = 0x401;
                        }
                    } else {
                        msg.what = 0x404;
                    }
                    mhandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static void loginByToken(final String userNumber,final Handler mhandler){
        final String url = String.format(UrlConstant.tokenUrl,userNumber,UserConstant.USER_TOKEN);
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                String result;
                try {
                    result = NetWorkUtil.httpGet(url);
                    if (result != null) {
                        if (!result.equalsIgnoreCase("wrong token")) {
                            UserConstant.USER_ACCOUNT = userNumber;
                            msg.what = 0x200;
                        } else {
                            msg.what = 0x401;
                        }
                    } else {
                        msg.what = 0x404;
                    }
                    mhandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static void getInfoByNetWork(final String userNumber, final String passWord,final Handler mhandler){
        final String url = String.format(UrlConstant.getInfoUrl,userNumber,passWord);
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                JSONObject jsonObject;
                String result;
                try {
                    result = NetWorkUtil.httpGet(url);
                    if (result != null) {
                        if (!result.equalsIgnoreCase("wrong password")) {
                            jsonObject = new JSONObject(result);
                            String type = jsonObject.getString("type");
                            if(type.equals("1")){
                                UserConstant.USER_CHARACTER = "patriarch";
                            }else if(type.equals("2")){
                                UserConstant.USER_CHARACTER = "teacher";
                            }
                            UserConstant.USER_AVATAR_PATH = jsonObject.getString("avatar_path");
                            UserConstant.USER_ACCOUNT = userNumber;
                            UserConstant.USER_ID = jsonObject.getString("uid");
                            UserConstant.USER_NAME = jsonObject.getString("name");
                            UserConstant.USER_SEX = (jsonObject.getString("sex")).equals("1")?"先生":"女士";
                            UserConstant.USER_CHILD_NAME = jsonObject.getString("description");
                            UserConstant.USER_PASSWORD = passWord;
                            UserConstant.USER_GRADE = (jsonObject.get("class_name")).toString();
                            UserConstant.USER_GRADIAN = jsonObject.getString("role");
                            UserConstant.USER_CONTACT = jsonObject.getString("phone");
                            jsonObject.put("password",passWord);
                            jsonObject.put("account",userNumber);
                            if(StorageUtil.saveAsJson(StorageUtil.getInfoDir(), "Info", jsonObject.toString()))
                                downloadIcon(UserConstant.USER_AVATAR_PATH,mhandler);
                            else
                                msg.what = 0x600;
                        } else {
                            msg.what = 0x401;
                        }
                    } else {
                        msg.what = 0x404;
                    }
                    mhandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private static void downloadIcon(final String link,final Handler mhandler){
        final String imageName = link.substring(link.lastIndexOf("/") + 1, link.lastIndexOf(".")) + ".png";
        final String links = link + "?imageMogr2/quality/"+"50";
        new Thread() {
            public void run() {
                Bitmap bitmap;
                JSONObject jsonObject = UserModel.retrieveInfo();
                Message msg = new Message();
                try {
                    HashMap<String, Object> item = new HashMap<String, Object>();
                    URL url = new URL(links);
                    InputStream is = url.openStream();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = false;
                    int imageHeight = options.outHeight;
                    int imageWidth = options.outWidth;
                    int s = imageHeight * imageWidth;
                    if(s>10000){
                        options.inSampleSize = s/100;
                    }else {
                        options.inSampleSize = 2;
                    }
                    try {
                        bitmap = BitmapFactory.decodeStream(is,null,options);
                        StorageUtil.saveAsImage(imageName, bitmap);
                        UserConstant.USER_AVATAR_PATH = imageName;
                        jsonObject.remove("avatar_path");
                        jsonObject.put("avatar_path",imageName);
                        StorageUtil.saveAsJson(StorageUtil.getInfoDir(), "Info", jsonObject.toString());
                        msg.what = 0x201;
                    }catch (OutOfMemoryError e){
                        e.printStackTrace();
                        msg.what = 0x600;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    msg.what = 0x600;
                }
                mhandler.sendMessage(msg);
            }
        }.start();
    }

    public static JSONObject retrieveInfo(){
        JSONObject jsonObject = null;
        String info;
        info = StorageUtil.retrieveFromFile(StorageUtil.getInfoDir(),"Info.json");
        try {
            if(info!=null)
                jsonObject = new JSONObject(info);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    //忘记密码
    public void forgetPassword(){

    }

    //获取班级列表方法
    public static void getClassesList(final Handler mhandler){
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                try {
                    String classes = NetWorkUtil.httpGet(UrlConstant.getClassUrl);
                    if(classes!=null){
                        UserConstant.CLASS_LIST = new JSONArray(classes);
                        msg.what = 0x405;
                    }else{
                        msg.what = 0x404;
                    }
                    mhandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //获取班级列表方法
    public static void getSubjectsList(final Handler mhandler){
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                try {
                    String classes = NetWorkUtil.httpGet(UrlConstant.getSubjectUrl);
                    if(classes!=null){
                        UserConstant.SUBJECTLIST = new JSONArray(classes);
                        msg.what = 0x408;
                    }else{
                        msg.what = 0x404;
                    }
                    mhandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public register getRegister(Handler mHandler){
        return new register(mHandler);
    }

    public class register{
        Handler mHandler;
        String account;
        String password;
        String type;
        String name;
        String sex;
        String description;
        String role;
        String classid;
        String phone;
        String iconUrl;

        register(Handler mHandler){
            this.mHandler = mHandler;
        }

        public void setAccount(String account) {
            this.account = account;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public void setClassid(String classid) {
            this.classid = classid;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public void setType(String type){this.type = type;}

        public void setIconUrl(String iconUrl){this.iconUrl = iconUrl;}

        public void setSex(String sex) {
            this.sex = sex;
        }

        public String getAccount(){return this.account;}

        public void checkIfRegisted(){
            final String url = String.format(UrlConstant.registedUrl,this.account);
            new Thread(){
                Message msg = new Message();
                @Override
                public void run(){
                    mHandler.sendEmptyMessage(0x100);
                    try {
                        JSONObject result = NetWorkUtil.httpGetVerbose(url);
                        if(result!=null){
                            if((result.getString("status")).equalsIgnoreCase("200")&&
                                    result.getString("msg").equalsIgnoreCase("ok"))
                                msg.what = 0x402;
                            else
                                msg.what = 0x403;
                        }else{
                            msg.what = 0x404;
                        }
                        mHandler.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

        public void submit(){
            final String url = String.format(UrlConstant.registUrl,this.account,this.password,
                    this.type,this.name,this.sex,this.description,this.role,this.classid,this.phone);
            new Thread(){
                Message msg = new Message();
                @Override
                public void run(){
                    try {
                        JSONObject result = NetWorkUtil.httpGetVerbose(url);
                        if(result!=null){
                            if((result.getString("status")).equalsIgnoreCase("200"))
                                msg.what = 0x200;
                            else
                                msg.what = 0x401;
                        }else{
                            msg.what = 0x404;
                        }
                        mHandler.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

        public boolean save() {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("account",this.account);
                jsonObject.put("password",this.password);
                jsonObject.put("type",this.type);
                jsonObject.put("name",this.name);
                jsonObject.put("sex",this.sex);
                jsonObject.put("description",this.description);
                jsonObject.put("role",this.role);
                jsonObject.put("classid",this.classid);
                jsonObject.put("phone",this.phone);
                jsonObject.put("avatar_path",this.iconUrl);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return StorageUtil.saveAsJson(StorageUtil.getInfoDir(), "Info", jsonObject.toString());
        }

        public void updateUserConstant(){
            if(type.equals("1")){
                UserConstant.USER_CHARACTER = "patriarch";
            }else if(type.equals("2")){
                UserConstant.USER_CHARACTER = "teacher";
            }
            UserConstant.USER_ACCOUNT = this.account;
            UserConstant.USER_PASSWORD = this.password;
            UserConstant.USER_AVATAR_PATH = this.iconUrl;
        }
    }
}
